module service.FriendService;

import repository;
import model;
import client.MsgServerClient;
import msgtrans;
import hunt.logging;
import message.Constants;
import message.MsgDefine;
import std.conv : to;

class FriendService {

  static ChatMap processChatMap(int index, int size)
  {
    ChatMap mp = new ChatMap;

    auto friendRepo = new FriendApplyRepository();
    auto userRepo = new UserRepository;

    FriendApply[] friends = friendRepo.getAll();
    foreach(FriendApply friend ; friends)
    {
        if (friend.id % size == index)
        {
          GroupInfo cm = new GroupInfo;
          cm.groupId = friend.id;
          cm.memberId ~= friend.userId;
          cm.memberId ~= friend.friendId;
          mp.map ~= cm;
        }
        else
        {
          continue;
        }
    }
    auto groupRepo = new GroupRepository();
    ChatGroup[] groups =  groupRepo.getAll();

    foreach(ChatGroup group ; groups)
    {
       if (group.id % size == index)
       {
         GroupInfo cm = new GroupInfo;
         cm.groupId = group.id;
         auto groupUserRepo = new GroupUserRepository();
         GroupUser[] users =  groupUserRepo.findAllByID(group.id);
         foreach (GroupUser user ; users)
         {
            cm.memberId ~= user.userId;
         }
         mp.map ~= cm;
       }
    }

    auto onlineUser = userRepo.findAllOnline();
    foreach(int id ; onlineUser)
    {
       if (id % size == index)
       {
          mp.onlineMember ~= id;
       }else
       {
          continue;
       }
    }
    return mp;
  }

  static void processDeleteFriend(string userId,string friendId)
  {
      auto friendRep = new FriendRepository();
      friendRep.deleteFriend(userId,friendId);
  }

  static void setMsgRead(string userId, string chatId, long timestamp)
  {
    auto friendRep = new FriendRepository();
    friendRep.updateMsgRead(userId,chatId,timestamp);
  }

  static bool setContactAliasName(string userId, string chatId, string aliasName)
  {
    auto friendRep = new FriendRepository();
    return friendRep.setAliasName(userId,chatId,aliasName);
  }

  static bool isSelf(string chatId, string userId)
  {
    auto friendRep = new FriendRepository();
    Friend[] friend = friendRep.findAllBychatId(to!int(chatId));
    if(friend.length != 0 &&  friend[0].userId == to!uint(userId) && friend[0].friendId == to!uint(userId))
    {
        return true;
    }
    return false;
  }
}

